package edu.zjut.yzj.backend.consumer;

import com.alibaba.fastjson.JSONObject;
import edu.zjut.yzj.backend.consumer.utils.Game;
import edu.zjut.yzj.backend.consumer.utils.JwtAuthentication;
import edu.zjut.yzj.backend.mapper.BotMapper;
import edu.zjut.yzj.backend.mapper.RecordMapper;
import edu.zjut.yzj.backend.mapper.UserMapper;
import edu.zjut.yzj.backend.pojo.Bot;
import edu.zjut.yzj.backend.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/websocket/{token}")  // 注意不要以'/'结尾
public class WebSocketServer {

    private Session session = null;

    private User user;

    final public static ConcurrentHashMap<Integer, WebSocketServer> users = new ConcurrentHashMap<>();

    public static RestTemplate restTemplate;

    private static UserMapper userMapper;
    public static RecordMapper recordMapper;
    public Game game=null;

    private static BotMapper botMapper;

    public Game getGame() {
        return this.game;
    }

    private final static String addPlayerUrl = "http://127.0.0.1:3001/player/add";
    private final static String removePlayerUrl = "http://127.0.0.1:3001/player/remove";

    @Autowired
    public void setBotMapper(BotMapper botMapper) {
        WebSocketServer.botMapper = botMapper;
    }

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        WebSocketServer.restTemplate = restTemplate;
    }

    @Autowired
    public void setRecordMapper(RecordMapper recordMapper) {
        WebSocketServer.recordMapper = recordMapper;
    }

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        WebSocketServer.userMapper = userMapper;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) throws IOException {
        // 打印线程信息
        System.out.println("当前线程名： " + Thread.currentThread().getName());
        System.out.println("当前线程id： "+ Thread.currentThread().getId());
        System.out.println("当前对象是："+this);
        // 建立连接
        this.session=session;
        System.out.println("连接建立！");

        Integer userId = JwtAuthentication.getUserId(token);

        this.user= userMapper.selectById(userId);


        if (user != null) {
            users.put(userId,this);
            System.out.println(user);
            System.out.println(users);
            System.out.println("WebSocketServer对象的个数是： "+users.size());;
        }else {
            session.close();
        }


    }

    @OnClose
    public void onClose() {
        // 关闭链接
        System.out.println("突然断电了，连接关闭！");
        if (this.users != null) {
            users.remove(this.user.getId());
            LinkedMultiValueMap<String, String> data = new LinkedMultiValueMap<>();
            data.add("user_id", this.user.getId().toString());

            restTemplate.postForObject(
                    removePlayerUrl,
                    data,
                    String.class
            );
        }
    }

    public static void startGame(Integer aId, Integer aBotId,Integer bId, Integer bBotId) {
        User a = userMapper.selectById(aId);
        User b = userMapper.selectById(bId);
        Bot botA = botMapper.selectById(aBotId);
        Bot botB = botMapper.selectById(bBotId);

        Game game = new Game(13, 14, 20,a.getId(),botA,b.getId(),botB);
        game.createMap();
        if( users.get(a.getId())!=null)
            users.get(a.getId()).game = game;
        if(users.get(b.getId())!=null)
            users.get(b.getId()).game = game;

        game.start();

        JSONObject respGame = new JSONObject();
        respGame.put("a_id", game.getPlayerA().getId());
        respGame.put("a_sx", game.getPlayerA().getSx());
        respGame.put("a_sy", game.getPlayerA().getSy());
        respGame.put("b_id", game.getPlayerB().getId());
        respGame.put("b_sx", game.getPlayerB().getSx());
        respGame.put("b_sy", game.getPlayerB().getSy());
        respGame.put("map", game.getG());

        JSONObject respA = new JSONObject();
        respA.put("event", "start-matching");
        respA.put("opponent_username", b.getUsername());
        respA.put("opponent_photo", b.getPhoto());
        respA.put("game", respGame);
        if( users.get(a.getId())!=null)
            users.get(a.getId()).sendMessage(respA.toJSONString());

        JSONObject respB = new JSONObject();
        respB.put("event", "start-matching");
        respB.put("opponent_username", a.getUsername());
        respB.put("opponent_photo", a.getPhoto());
        respB.put("game", respGame);
        if(users.get(b.getId())!=null)
            users.get(b.getId()).sendMessage(respB.toJSONString());
    }

    private void stopMatching() {
        System.out.println("取消匹配");
        LinkedMultiValueMap<String, String> data = new LinkedMultiValueMap<>();
        data.add("user_id", this.user.getId().toString());
        restTemplate.postForObject(
                removePlayerUrl,
                data,
                String.class
        );


    }

    private void move(int direction) {
        if(this.game.getPlayerA().getId().equals(user.getId())){//当前玩家是玩家A
            if(game.getPlayerA().getBotId().equals(-1))
                game.setNextStepA(direction);
        } else if (this.game.getPlayerB().getId().equals(user.getId())) {
            if(game.getPlayerB().getBotId().equals(-1))
                game.setNextStepB(direction);
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {

        JSONObject data = JSONObject.parseObject(message);
        String event = data.getString("event");
        if("start-matching".equals(event)){
            startMatching(data.getInteger("bot_id"));
        }else if("stop-matching".equals(event)){
            stopMatching();
        }else if("move".equals(event)){
            move(data.getInteger("direction"));
        }
    }

    private void startMatching(Integer botId) {
        System.out.println("开始匹配");
        LinkedMultiValueMap<String, String> data = new LinkedMultiValueMap<>();
        data.add("user_id", this.user.getId().toString());
        data.add("rating",this.user.getRating().toString());
        data.add("bot_id",botId.toString());
        restTemplate.postForObject(
                addPlayerUrl,
                data,
                String.class
        );

    }

    @OnError
    public void onError(Session session, Throwable error) {

        error.printStackTrace();
    }

    public void sendMessage(String message) {
        synchronized (this.session) {
            try {
                this.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
